package com.chat.utils;

import com.chat.enums.MessageByUserNameAndIdEnum;
import com.chat.response.message.BaseMessageResponse;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisMessageUtil {
    private static final String OFFLINE_MESSAGE_KEY_FORMAT = "%d:%s";

    @Resource
    private RedisUtil redisUtil;

    public void addOfflineMessage(Long userId, BaseMessageResponse message) {
        String redisKey = getOfflineMessageKey(userId);
        redisUtil.setCacheList(redisKey, message);
    }

    public List<BaseMessageResponse> getAndClearOfflineMessages(Long userId) {
        String redisKey = getOfflineMessageKey(userId);
        List<BaseMessageResponse> messages = redisUtil.getCacheList(redisKey);
        redisUtil.deleteList(redisKey);
        return messages;
    }

    private String getOfflineMessageKey(Long userId) {
        return String.format(OFFLINE_MESSAGE_KEY_FORMAT, userId, MessageByUserNameAndIdEnum.OFFLINE_MESSAGE_LIST);
    }
}

